<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Monda:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.jpg?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.jpg?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.jpg?v=5.1.4">


  <link rel="mask-icon" href="/images/favicon.jpg?v=5.1.4" color="#222">





  <meta name="keywords" content="React,JavaScript,Js框架," />





  <link rel="alternate" href="/atom.xml" title="时光无言流转" type="application/atom+xml" />






<meta name="description" content="概述React 起源于 Facebook 的内部项目，并于2013年5月开源。更多精彩见React 官网">
<meta name="keywords" content="React,JavaScript,Js框架">
<meta property="og:type" content="article">
<meta property="og:title" content="React学习-基于v16.7.0">
<meta property="og:url" content="http://yoursite.com/2018/12/25/React学习-基于v16-7-0/index.html">
<meta property="og:site_name" content="时光无言流转">
<meta property="og:description" content="概述React 起源于 Facebook 的内部项目，并于2013年5月开源。更多精彩见React 官网">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://yoursite.com/2018/12/25/React学习-基于v16-7-0/react.jpeg">
<meta property="og:updated_time" content="2018-12-28T08:35:42.993Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="React学习-基于v16.7.0">
<meta name="twitter:description" content="概述React 起源于 Facebook 的内部项目，并于2013年5月开源。更多精彩见React 官网">
<meta name="twitter:image" content="http://yoursite.com/2018/12/25/React学习-基于v16-7-0/react.jpeg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2018/12/25/React学习-基于v16-7-0/"/>





  <title>React学习-基于v16.7.0 | 时光无言流转</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?665c65036126c4bdb37400c941c9fc0b";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
    <a href="https://github.com/Somnus007" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#70B7FD; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">时光无言流转</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">回首向来萧瑟处，归去，也无风雨也无晴。</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2018/12/25/React学习-基于v16-7-0/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="时光无言流转">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="时光无言流转">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">React学习-基于v16.7.0</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-12-25T16:05:13+08:00">
                2018-12-25
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/前端/" itemprop="url" rel="index">
                    <span itemprop="name">前端</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i>阅读数</i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1.8k 字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  8 分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="/2018/12/25/React学习-基于v16-7-0/react.jpeg" alt="Alt React学习笔记" title="React学习笔记"></p>
<h2 id="概述"><a href="#概述" class="headerlink" title="概述"></a>概述</h2><p>React 起源于 Facebook 的内部项目，并于2013年5月开源。更多精彩见<a href="https://reactjs.org/" title="React 官网" target="_blank" rel="noopener">React 官网</a></p>
<a id="more"></a>
<h3 id="声明式渲染"><a href="#声明式渲染" class="headerlink" title="声明式渲染"></a>声明式渲染</h3><p>先来说明一下<strong>命令式编程</strong>和<strong>声明式编程</strong>：<br><strong>命令式编程关注怎么做</strong>，通俗点说就是我们通过一行一行代码让机器照着一步一步的去做。例如我有一个数组，然后想通过它得到每个值都是它的值两倍的数组：</p>
<pre><code>const originArr = [1,2,3]; // 原始数组
const resultArr = []; // 定义一个空数组
for(let i = 0;i &lt; originArr.length;i++){ // 遍历原始数组，然后将每个值乘于2之后添加到空数组中
    resultArr.push(originArr[i] * 2)
}
</code></pre><p><strong>声明式编程关注做什么</strong>，就是我们的目的。同样的例子适用声明式编程：</p>
<pre><code>const originArr = [1,2,3]; // 原始数组
const resultArr = originArr.map(item =&gt; item * 2); // 遍历数组由map方法代为实现，而我们只需要关注我们要做什么：即把每个值乘于2
</code></pre><p>那么react的声明式渲染体现在什么地方呢？简单点说就是react独创的<strong>JSX</strong>语法，一种把html和js结合起来的成果，例如：</p>
<pre><code>const title = &lt;h3&gt;This is a title&lt;/h3&gt; ; 
</code></pre><p>上述代码中<code>&lt;h3&gt;This is a title&lt;/h3&gt;</code> 既非html也非字符串，我们可以叫它react element，实际上它在被react渲染成真实DOM之前只是一个普通的js对象，后面会有介绍。<br>React使用JSX语法让我们只需要是关注我们想要做什么，输入的state或者props，输出的UI界面，而不用分心关注于原生的DOM操作。</p>
<h3 id="组件化"><a href="#组件化" class="headerlink" title="组件化"></a>组件化</h3><p>在React中一切皆组件，组件是React中最基本的单元结构。大到整个页面，小到一个按钮或者弹窗都可以成为一个组件。</p>
<h3 id="可移植性强"><a href="#可移植性强" class="headerlink" title="可移植性强"></a>可移植性强</h3><p>React不仅可以在web端使用，它还可以借助nodejs在server端渲染，还可以借助 React Native 开发移动端应用。</p>
<h2 id="使用React"><a href="#使用React" class="headerlink" title="使用React"></a>使用React</h2><p>React并不强制开发者在项目中完全使用或者完全不用，所以我们可是尝试性的在项目的某个部分使用React，也可以完整的使用React完成项目。</p>
<h3 id="局部使用React"><a href="#局部使用React" class="headerlink" title="局部使用React"></a>局部使用React</h3><p>可以在html中通过script标签引入react框架的CDN链接：</p>
<pre><code>&lt;script src=&quot;https://unpkg.com/react@16/umd/react.production.min.js&quot; crossorigin&gt;&lt;/script&gt;
&lt;script src=&quot;https://unpkg.com/react-dom@16/umd/react-dom.production.min.js&quot; crossorigin&gt;&lt;/script&gt;
</code></pre><p>这是React官方给出的CDN 链接，考虑到网络问题，我们可以自由选择其他的可靠资源，或者下载之后上传并使用自己的CDN服务。完整的Demo请参考 <a href="https://gist.github.com/gaearon/6668a1f6986742109c00a581ce704605" title="局部使用React" target="_blank" rel="noopener">局部使用React</a></p>
<p><strong>如果想使用JSX，需要额外引入，详情请见<a href="http://reactjs.org/docs/add-react-to-a-website.html#add-jsx-to-a-project" title="引入JSX" target="_blank" rel="noopener">引入JSX</a></strong></p>
<h3 id="完整使用React"><a href="#完整使用React" class="headerlink" title="完整使用React"></a>完整使用React</h3><p>基于React的框架也有不少，下面这几个是官方推荐使用的：</p>
<ul>
<li>创建一个SPA，使用<a href="https://github.com/facebook/create-react-app#create-react-app-" title="Create React App" target="_blank" rel="noopener">Create React App</a></li>
<li>如果想使用react+nodejs创建后端渲染（SSR）应用，可以使用<a href="https://nextjs.org/" title="Next.js" target="_blank" rel="noopener">Next.js</a></li>
<li>创建一个静态页面网站，可以使用<a href="https://www.gatsbyjs.org/" title="Gatsby" target="_blank" rel="noopener">Gatsby</a></li>
</ul>
<pre><code>npx create-react-app my-app
cd my-app
npm start
</code></pre><p>可以通过上面的命令行完成使用creat react app来创建一个react 应用。</p>
<h2 id="JSX语法"><a href="#JSX语法" class="headerlink" title="JSX语法"></a>JSX语法</h2><pre><code>const el = (
    &lt;div className=&quot;box&quot; customizeProp=&quot;test&quot;&gt;
        &lt;button onClick={handleClick}&gt;Click me&lt;/button&gt;
    &lt;/div&gt;
)

const el = React.createElement(
    &apos;div&apos;,
    {className: &apos;box&apos;,customizeProp:&apos;test&apos;},
    React.createElement(
        &apos;button&apos;,
        {onClick:handleClick},
        &apos;Click me&apos;
    )
);
</code></pre><p>点语法：</p>
<pre><code>const MyComponents = {
    DatePicker: function DatePicker(props) {
        return &lt;div&gt;Imagine a {props.color} datepicker here.&lt;/div&gt;;
    }
}

function BlueDatePicker() {
    return &lt;MyComponents.DatePicker color=&quot;blue&quot; /&gt;;
}
</code></pre><p>展开符属性写法：</p>
<pre><code>function App2() {
const props = {firstName: &apos;Ben&apos;, lastName: &apos;Hector&apos;};
return &lt;Greeting {...props} /&gt;;
}
</code></pre><h2 id="react-lazy-load"><a href="#react-lazy-load" class="headerlink" title="react lazy load"></a>react lazy load</h2><pre><code>const OtherComponent = React.lazy(() =&gt; import(&apos;./OtherComponent&apos;));

&lt;div&gt;
  &lt;Suspense fallback={&lt;div&gt;Loading...&lt;/div&gt;}&gt;  // 组件加载过程中出现，类似传统loading效果
    &lt;section&gt;
      &lt;OtherComponent /&gt;
    &lt;/section&gt;
  &lt;/Suspense&gt;
&lt;/div&gt;
</code></pre><h2 id="context"><a href="#context" class="headerlink" title="context"></a>context</h2><pre><code>定义：
const MyContext = React.createContext(defaultValue);

使用：
父组件或者以上：
&lt;MyContext.Provider value={theme}&gt;
    &lt;ThemedButton changeTheme={this.toggleTheme} /&gt;
&lt;/MyContext.Provider&gt;
子组件：
class ThemedButton extends React.Component {
    static contextType = MyContext;  // 1 与3的点操作符方式二选一
    render() {
        let props = this.props;
        let theme = this.context;  // 2
        return (
        &lt;button
            {...props}
            style={{backgroundColor: theme.background}}
        /&gt;
        );
        // 或者不使用1&amp;2或3&amp;2，使用Consumer，如果在一个组件里想使用多个context，只能使用Consumer+Provider，进行层层包裹
        &lt;MyContext.Consumer&gt;
        {(theme) =&gt; (
            &lt;button
                {...props}
                style={{backgroundColor: theme.background}}
            /&gt;
        )}
        &lt;/MyContext.Consumer&gt;
    }
}
ThemedButton.contextType = MyContext; // 3

export default ThemedButton;
</code></pre><h2 id="error-boundary"><a href="#error-boundary" class="headerlink" title="error boundary"></a>error boundary</h2><pre><code>class ErrorBoundary extends React.Component {
    constructor(props) {
        super(props);
        this.state = { hasError: false };
    }

    static getDerivedStateFromError(error) {    // 1
        // Update state so the next render will show the fallback UI.
        return { hasError: true };
    }

    componentDidCatch(error, info) {     // 2
        // You can also log the error to an error reporting service
        logErrorToMyService(error, info);
    }

    render() {
        if (this.state.hasError) {
        // You can render any custom fallback UI
        return &lt;h1&gt;Something went wrong.&lt;/h1&gt;;
        }

        return this.props.children; 
    }
}
</code></pre><p>如果有1或者2或者同时存在，则为error boundary组件，用法如下：</p>
<pre><code>&lt;ErrorBoundary&gt;
    &lt;Children /&gt;
&lt;/ErrorBoundary&gt;
</code></pre><p>error boundary比较类似try{}catch(){}中catch代码块，另外需要注意的是<strong>只有class组件可以成为error boundary，函数组件是不行的，这主要是因为函数组件是不支持组件自有的state特性的</strong>。error boundary几乎可以捕捉到它的子组件任何地方和任何时候的错误，但下列情况的错误是捕捉不到的：</p>
<ul>
<li>事件处理函数中错误（可以考虑使用try/catch进行错误捕捉）</li>
<li>异步代码中错误</li>
<li>后端渲染部分的错误</li>
<li>以及error boundary自身的报错</li>
</ul>
<h2 id="ref的传递"><a href="#ref的传递" class="headerlink" title="ref的传递"></a>ref的传递</h2><p>创建一个组件FancyButton，如果我们想要通过ref访问他的自组件button，</p>
<pre><code>1. 通过createRef创建一个ref
2. 将ref放入FancyButton的ref属性中
3. FancyButton通过React.forwardRef将ref传递至button
4. 此时当我们访问ref.current时将指向button

const FancyButton = React.forwardRef((props, ref) =&gt; (   // 此处可使用function name(){}来代替匿名函数，以实现自定义函数名称
    &lt;button ref={ref} className=&quot;FancyButton&quot;&gt;
        {props.children}
    &lt;/button&gt;
));
You can now get a ref directly to the DOM button:
const ref = React.createRef();
&lt;FancyButton ref={ref}&gt;
    Click me!
&lt;/FancyButton&gt;;
</code></pre><p>在高阶组件中传递ref：</p>
<pre><code>function logProps(Component) {
    class LogProps extends React.Component {
        componentDidUpdate(prevProps) {
            console.log(&apos;old props:&apos;, prevProps);
            console.log(&apos;new props:&apos;, this.props);
        }

        render() {
            const {forwardedRef, ...rest} = this.props;

            // Assign the custom prop &quot;forwardedRef&quot; as a ref
            return &lt;Component ref={forwardedRef} {...rest} /&gt;;
        }
    }

    // Note the second param &quot;ref&quot; provided by React.forwardRef.
    // We can pass it along to LogProps as a regular prop, e.g. &quot;forwardedRef&quot;
    // And it can then be attached to the Component.
    return React.forwardRef((props, ref) =&gt; {
        return &lt;LogProps {...props} forwardedRef={ref} /&gt;;
    });
}
</code></pre><h2 id="Fragments"><a href="#Fragments" class="headerlink" title="Fragments"></a>Fragments</h2><ul>
<li>可以单独从react中引用：import {Fragment} from ‘react’</li>
<li>也可以不单独引用， <code>&lt;React.Fragment&gt;&lt;Children /&gt;&lt;/React.Fragment&gt;</code></li>
<li>还可以使用简写语法 <code>&lt;&gt;&lt;Children /&gt;&lt;/&gt;</code></li>
</ul>
<p>渲染出的结果将会是单纯的<code>&lt;Children /&gt;</code>,而不存在任何父元素</p>
<h2 id="HOC（高阶组件）"><a href="#HOC（高阶组件）" class="headerlink" title="HOC（高阶组件）"></a>HOC（高阶组件）</h2><p>定义： 一个函数，接受一个react组件作为参数，并且返回一个react组件，这个函数就称为高阶组件，<strong>高阶组件是一个纯函数，他不会改变作为参数的组件</strong></p>
<pre><code>function logProps(WrappedComponent) {
    return class extends React.Component {
        componentWillReceiveProps(nextProps) {
            console.log(&apos;Current props: &apos;, this.props);
            console.log(&apos;Next props: &apos;, nextProps);
        }
        render() {
            // Wraps the input component in a container, without mutating it. Good!
            return &lt;WrappedComponent {...this.props} /&gt;;
        }
    }
}
</code></pre>
      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div></div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="时光无言流转 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/React/" rel="tag"># React</a>
          
            <a href="/tags/JavaScript/" rel="tag"># JavaScript</a>
          
            <a href="/tags/Js框架/" rel="tag"># Js框架</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/11/29/Hexo-GitHub搭建个人博客/" rel="next" title="Hexo+GitHub构建个人博客">
                <i class="fa fa-chevron-left"></i> Hexo+GitHub构建个人博客
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/08/21/JS按位操作符/" rel="prev" title="JS按位操作符">
                JS按位操作符 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MTM0OS8xNzg5Ng=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
      <div id="sidebar-dimmer"></div>
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.jpg"
                alt="时光无言流转" />
            
              <p class="site-author-name" itemprop="name">时光无言流转</p>
              <p class="site-description motion-element" itemprop="description">回首向来萧瑟处，归去，也无风雨也无晴。</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">4</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">1</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/Somnus007" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:somnus.sxy@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                友情链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.baidu.com/" title="Allen" target="_blank">Allen</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.baidu.com/" title="Zero" target="_blank">Zero</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#概述"><span class="nav-number">1.</span> <span class="nav-text">概述</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#声明式渲染"><span class="nav-number">1.1.</span> <span class="nav-text">声明式渲染</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#组件化"><span class="nav-number">1.2.</span> <span class="nav-text">组件化</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#可移植性强"><span class="nav-number">1.3.</span> <span class="nav-text">可移植性强</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用React"><span class="nav-number">2.</span> <span class="nav-text">使用React</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#局部使用React"><span class="nav-number">2.1.</span> <span class="nav-text">局部使用React</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#完整使用React"><span class="nav-number">2.2.</span> <span class="nav-text">完整使用React</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#JSX语法"><span class="nav-number">3.</span> <span class="nav-text">JSX语法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#react-lazy-load"><span class="nav-number">4.</span> <span class="nav-text">react lazy load</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#context"><span class="nav-number">5.</span> <span class="nav-text">context</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#error-boundary"><span class="nav-number">6.</span> <span class="nav-text">error boundary</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#ref的传递"><span class="nav-number">7.</span> <span class="nav-text">ref的传递</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Fragments"><span class="nav-number">8.</span> <span class="nav-text">Fragments</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#HOC（高阶组件）"><span class="nav-number">9.</span> <span class="nav-text">HOC（高阶组件）</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2017 &mdash; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-snowflake-o"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">时光无言流转</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">站点字数统计&#58;</span>
    
    <span title="站点字数统计">4.4k 字</span>
  
</div>









        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      访客数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人
    </span>
  

  
    <span class="site-pv">
      总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
